package com.news;

import android.app.Activity;
import android.util.DisplayMetrics;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

public class Utils {

  private static Utils    selfObj         = null;

  private static Activity activity        = null;

  final static int        GESTURE_INVALID = 0;

  final static int        GESTURE_LEFT    = 1;

  final static int        GESTURE_RIGHT   = 2;

  private static int      coordsX[]       = new int[5];

  private static int      coordsY[]       = new int[5];

  public Utils(Activity activity) {
    Utils.setActivity(activity);
  }

  public static int getScreenWidth(Activity activity) {
    Utils.setActivity(activity);
    int width = 0;
    width = activity.getWindowManager().getDefaultDisplay().getWidth();
    return width;
  }

  public static DisplayMetrics getDisplayMetricsObj(Activity activity) {
    Utils.setActivity(activity);
    DisplayMetrics dm = new DisplayMetrics();
    dm = activity.getResources().getDisplayMetrics();
    return dm;
  }

  /**
   * set no title and full screen
   * 
   * @return void
   */
  public static void setFullScreen(Activity activity) {
    Utils.setActivity(activity);
    // 设置无标题
    Utils.activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
    // 设置全屏
    Utils.activity.getWindow().setFlags(
        WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
  }

  public static int getGesture(float x, float y) {
    int range = 10, horizontal = 0, vertical = 0;
    if (coordsX.length < 5)
      Utils.coordsX[coordsX.length] = (int) x;
    if (coordsY.length < 5)
      Utils.coordsY[coordsY.length] = (int) y;

    if (coordsX.length < 3 || coordsY.length < 3)
      return GESTURE_INVALID;
    horizontal = coordsY[0] - coordsY[coordsY.length - 1];
    if (horizontal > 0) {
      float gesterY = average(coordsY);
      if (horizontal > gesterY - range) {
        return GESTURE_LEFT;
      }
      return GESTURE_INVALID;
    }
    else {
      return GESTURE_INVALID;
    }
  }

  public static DisplayMetrics getDisplayMetricsObj() {
    DisplayMetrics dm = new DisplayMetrics();
    dm = Utils.activity.getResources().getDisplayMetrics();
    return dm;
  }

  private static void setActivity(Activity a) {
    if (Utils.activity == null) {
      Utils.activity = a;
    }
  }

  public void showToast(String mes) {
    Toast.makeText(Utils.activity.getApplicationContext(), mes,
        Toast.LENGTH_LONG).show();
  }

  private static float average(int[] num) {
    if (num.length <= 0)
      return 0.0f;
    int sum = 0;
    for (int i = 0; i < num.length; i++) {
      sum += num[i];
    }
    return (float) sum / num.length;
  }

  public static Utils getInstance(Activity a) {
    if (selfObj == null) {
      selfObj = new Utils(a);
    }
    return selfObj;
  }
}
